<?php
/**
 * 得到文件保存路径
 */
function getPath(){
	$item = isset($_REQUEST['item'])?$_REQUEST['item']:'default';//item作为相册文件夹名称
	$pre = C('UPLOAD_PATH');
	$subdir = isset($_REQUEST['subdir'])?('/'.str_replace('|', '/', $_REQUEST['subdir'])):'';//子目录
	return $pre.$item.$subdir;
}

/**
 * 保存入库(文件的保存路径,上传后的文件名,上传前的文件名)
 */
function save2mysql($path,$newName,$oldName,$returnUrl=false){
	//得到当前上传图片大小容量和尺寸
	$temp_ = getimagesize($path);//图片尺寸
	$params['width']=$temp_[0];
	$params['height']=$temp_[1];
	$params['size'] = filesize($path);
	if($params['size']>0 AND ($unit=$params['size']/1024)<1024){
		$params['unit'] = number_format($unit,1).'KB';
	}elseif($unit>0 AND ($unit=$unit/1024)<1024){
		$params['unit'] = number_format($unit,1).'M';
	}elseif($unit>0 AND ($unit=$unit/1024)){
		$params['unit'] = number_format($unit,1).'G';
	}
	//保存后缀名
	$params['ext'] = str_replace('.','',strrchr($newName, '.'));
	//item 分类唯一名称/相册名称
	$item = isset($_REQUEST['item'])?$_REQUEST['item']:'default';
	$subdir = isset($_REQUEST['subdir'])?('/'.str_replace('|', '/', $_REQUEST['subdir'])):'';//子目录
	$url = 'share/images/'.$item.$subdir.'/'.$newName;
	//data
	$data=array(
				'title'=>$oldName,
				'item'=>$item,
				'link'=>$url,
				'adddate'=>date("Y-m-d H:i:s"),
				'params'=>$params,
				'table'=>isset($_REQUEST['table'])?$_REQUEST['table']:'',
				'idid'=>isset($_REQUEST['idid'])?(int)$_REQUEST['idid']:0,
				//'admin'=>$_REQUEST['admin']
			   );
	//print_r($data);exit;
	/* 非梦幻框架时,请用下面这段 S */
		//dbInit();//db初始化
		//$sql = "INSERT INTO `{$dbs['dbprefix']}photo` (`title`,`item`,`link`,`adddate`,`params`,`table`,`idid`) 
		//		VALUES('{$data['title']}','{$data['item']}','{$data['link']}','{$data['adddate']}','{$data['params']}','{$data['table']}',{$data['idid']})";
		//$ok = mysql_query($sql);
		//mysql_close();
	/* 非梦幻框架时,请用下面这段 E */
	/* 梦幻框架 S */
	$ok = DB('photo')->clear()->add($data);
	/* 梦幻框架 E */
	//入库失败时
	if($returnUrl){
	    return $url;
	}else{
	    if(!$ok){
	        @unlink($path);//删除图片
	        die('{"jsonrpc" : "2.0", "error" : {"code": 177, "message": "Save to database is Failed."}, "id" : "id"}');
	    }
	}
}

/**
 * 初始化数据库 (注: 梦幻中用不到该函数, 用于非梦幻框架)
 */
/*function dbInit(){
	$dbConfig = false;
	$path = '../../Config/Database.php';
	if(file_exists($path)){
		$dbConfig = include_once($path);
	}
	if(is_array($dbConfig)){
		mysql_connect($dbConfig['dbhost'],$dbConfig['dbuser'],$dbConfig['dbpwd']);
		mysql_select_db($dbConfig['dbname']);
		mysql_query("set names utf8");
		return true;
	}else{
		return false;
	}
}*/